package com.orchard.orchardfarmmanagementsystem.controller;


import com.orchard.orchardfarmmanagementsystem.dto.EvaluationDTO;
import com.orchard.orchardfarmmanagementsystem.dto.TaskDTO;
import com.orchard.orchardfarmmanagementsystem.dto.TaskEvaluationDTO;
import com.orchard.orchardfarmmanagementsystem.dto.TaskFetchDTO;
import com.orchard.orchardfarmmanagementsystem.entity.Task;
import com.orchard.orchardfarmmanagementsystem.entity.User;
import com.orchard.orchardfarmmanagementsystem.service.TaskService;
import com.orchard.orchardfarmmanagementsystem.service.UserService;
import com.orchard.orchardfarmmanagementsystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api")
public class TaskController {

    @Autowired
    private TaskService taskService;


    @GetMapping("/tasks")
    @PreAuthorize("hasAuthority('PERM_READ_DATA')")
    public Result<List<TaskFetchDTO>> getAllTasks(@RequestParam Map<String, String> queryParams) {
        try {
            List<TaskFetchDTO> tasks = taskService.getAllTasks(queryParams);
            return Result.success("获取任务列表成功", tasks);
        } catch (Exception e) {
            return Result.error(50001, "获取任务列表失败");
        }
    }

    @PostMapping("/tasks")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result submitTask(@RequestBody TaskDTO task) {
        try {
            return taskService.createTask(task);

        } catch (Exception e) {
            return Result.error(50001, "任务提交失败");
        }
    }

    @PutMapping("/tasks/{taskId}/status")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result updateTaskStatus(@PathVariable Integer taskId, @RequestParam String status) {
        if (status == null || status.isEmpty()) {
            return Result.error(50001, "状态不能为空");
        }

        return taskService.updateTaskStatus(taskId, status);
    }


    @GetMapping("/tasks/completed")
    @PreAuthorize("hasAuthority('PERM_READ_DATA')")
    public Result<List<TaskEvaluationDTO>> fetchCompletedTasks() {
        try {
            List<TaskEvaluationDTO> taskEvaluationDTOS = taskService.fetchCompletedTasks();
            return Result.success("获取已完成任务列表成功",taskEvaluationDTOS);

        } catch (Exception e) {
            return Result.error(50001, "获取已完成任务列表失败");
        }
    }


}

